package com.wjk.cms.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.AbstractHttpMessage;
import org.apache.http.params.HttpParams;

import javax.net.ssl.SSLContext;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Slf4j
public class HttpUtil {

    /**
     * 创建带有会话httpclient对象
     *
     * @param isSSL ture：https协议请求；false：http协议请求
     * @return
     */
    public CloseableHttpClient createSSLClientDefault(boolean isSSL) {
        CookieStore sslcookies = new BasicCookieStore();
        CookieStore cookies = new BasicCookieStore();
        if (isSSL) {
            SSLContext sslContext = null;
            try {
                sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                    //信任所有
                    public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                        return true;
                    }
                }).build();
            } catch (KeyManagementException e) {
                log.error(e.getMessage(), e);
            } catch (NoSuchAlgorithmException e) {
                log.error(e.getMessage(), e);
            } catch (KeyStoreException e) {
                log.error(e.getMessage(), e);
            }
            if (sslContext != null) {
                SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
                return HttpClients.custom().setDefaultRequestConfig(RequestConfig.custom()
                        .setCookieSpec(CookieSpecs.STANDARD).build()).setSSLSocketFactory(sslsf).setDefaultCookieStore(sslcookies).build();

            } else {
                return HttpClients.custom().setDefaultRequestConfig(RequestConfig.custom()
                        .setCookieSpec(CookieSpecs.STANDARD).build()).setDefaultCookieStore(cookies).build();
            }
        } else {
            return HttpClients.custom().setDefaultRequestConfig(RequestConfig.custom()
                    .setCookieSpec(CookieSpecs.STANDARD).build()).setDefaultCookieStore(cookies).build();
        }
    }

    /**
     * 设置header参数
     *
     * @param methord
     * @param headerMap
     */
    public static void wrapperHeader(AbstractHttpMessage methord, Map<String, String> headerMap) {
        if (headerMap != null) {
            Iterator entries = headerMap.entrySet().iterator();
            while (entries.hasNext()) {
                Map.Entry<String, String> entry = (Map.Entry<String, String>) entries.next();
                String key = entry.getKey();
                String value = entry.getValue();
                methord.setHeader(key, value);
            }
        }
    }

    public Map<String, Object> sendHttpGet(CloseableHttpClient client, String sendUrl, Map<String, String> headerMap, boolean isSll, long systime) throws Exception {
        Map<String, Object> resultMap = new HashMap<>();
        HttpResponse httpResponse = null;
        try {
            HttpGet httpGet = new HttpGet(sendUrl);
            wrapperHeader(httpGet, headerMap);
            httpResponse = client.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            Header[] header = httpResponse.getAllHeaders();
            resultMap.put("httpEntity", httpEntity);
            resultMap.put("header", header);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw e;
        }
        return resultMap;
    }

    public Map<String, Object> sendHttpGetNoRedirect(CloseableHttpClient client, String sendUrl, Map<String, String> headerMap, boolean isSll, long systime) throws Exception {
        Map<String, Object> resultMap = new HashMap<>();
        HttpResponse httpResponse = null;
        try {
            HttpGet httpGet = new HttpGet(sendUrl);
            HttpParams params = httpGet.getParams();
            params.setParameter(ClientPNames.HANDLE_REDIRECTS, false);
            wrapperHeader(httpGet, headerMap);
            httpResponse = client.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            Header[] header = httpResponse.getAllHeaders();
            resultMap.put("httpEntity", httpEntity);
            resultMap.put("header", header);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw e;
        }
        return resultMap;
    }

    public Map<String, Object> sendHttpPost(CloseableHttpClient client, String sendUrl, Map<String, String> headerMap, List<NameValuePair> params, boolean isSll, long systime) throws Exception {
        Map<String, Object> resultMap = new HashMap<>();
        HttpResponse httpResponse = null;
        try {
            HttpPost post = new HttpPost(sendUrl);
            wrapperHeader(post, headerMap);
            post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
            httpResponse = client.execute(post);
            HttpEntity entity = httpResponse.getEntity();
            Header[] header = httpResponse.getAllHeaders();
            resultMap.put("httpEntity", entity);
            resultMap.put("header", header);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw e;
        }
        return resultMap;
    }

    public static String getContent(String url) throws IOException {
        HttpURLConnection httpConn = (HttpURLConnection) new URL(url).openConnection();
        httpConn.setRequestMethod("GET");
        httpConn.setDoOutput(true);
        System.setProperty("sun.net.client.defaultConnectTimeout", "120000");
        System.setProperty("sun.net.client.defaultReadTimeout", "120000");
        httpConn.setConnectTimeout(120000);
        httpConn.setReadTimeout(120000);
        int code = httpConn.getResponseCode();
        if (code != 200) return null;
        BufferedReader br = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
        StringBuffer infoSB = new StringBuffer();
        String resp = null;
        while ((resp = br.readLine()) != null) {
            infoSB.append(resp);
        }
        return infoSB.toString();
    }

    public static JSONObject getJson(String url) throws IOException {
        return JSON.parseObject(getContent(url));
    }

}
